#include <config.h>
#include <core.h>

char ** copy_argv;
char ** os_environ;
char ** os_argv;
int     os_argc;

static char * last_argv;

int32_t save_argv(int argc , char ** argv)
{
    os_argc = argc;
    os_argv = argv;
    os_environ = environ;

    copy_argv = malloc((argc+1)*sizeof(char*));
    if(copy_argv == NULL)
        return MSGD_ERROR;


    size_t  len;
    int i;

    for(i=0; i<argc; i++){
       len  = strlen(argv[i]) + 1;

       copy_argv[i] = malloc(len);
       if(copy_argv[i] == NULL)
          return MSGD_ERROR;

       (void)cpystrn((u_char*)copy_argv[i],(u_char*)argv[i],len);
       DEBUG("argc:%d argv[%d]:%s",i,i,copy_argv[i]);
    }
   
    copy_argv[i] = NULL;
  
    return MSGD_OK;    
}

int32_t init_setproctitle()
{
   char     *p;
   size_t    size;
   int       i;

   for(i=0; environ[i]; i++){
      size += strlen(environ[i]) + 1;
   }

   p = malloc(size);
   if(p == NULL)
     return MSGD_ERROR;

   last_argv = os_argv[0];
   for(i=0; i<os_argc; i++){
      if(last_argv == os_argv[0]){
         last_argv = os_argv[i] + strlen(os_argv[i]) + 1;
      }
   }


   for(i=0; environ[i]; i++){
      if(last_argv == environ[i]){
         size = strlen(environ[i]) + 1;
         last_argv = environ[i] + size; 
 
         (void)cpystrn((u_char*)p,(u_char*)environ[i],size);
         environ[i] = p;
         p += size;
      }
   }
 
   last_argv--;

   return MSGD_OK;
}

void set_proctitle(u_char * title)
{
    INFO("set_proctitle :%s",title);
    os_argv[1] = NULL;
    u_char *p;
    p = cpystrn((u_char*)os_argv[0],title,(last_argv - os_argv[0])); 

  
    if(last_argv - (char*)p > 0 ) 
      memset(p,0,last_argv - (char*)p);

    INFO("has set_proctitled :%s",os_argv[0]);
}
